package cn.csc.framework.rpc.config;

import cn.csc.framework.common.enums.AuthConstants;
import cn.hutool.core.util.StrUtil;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import io.seata.core.context.RootContext;
import io.seata.spring.annotation.GlobalTransactional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.stereotype.Component;

/**
 * @GlobalTransactional分布式事务拦截器
 * @author liuchuang
 * @version 1.0
 * @date 2024/1/8 11:03
 * @modify
 */
@Component
@ConditionalOnClass({RequestInterceptor.class, GlobalTransactional.class})
public class SeataRequestInterceptor implements RequestInterceptor {

    private static final Logger logger = LoggerFactory.getLogger(SeataRequestInterceptor.class);

    @Override
    public void apply(RequestTemplate template) {
        String currentXid = RootContext.getXID();
        if (StrUtil.isNotBlank(currentXid) && !template.url().startsWith(AuthConstants.CHECK_TOKEN_URI)
                && !template.url().startsWith(AuthConstants.CHECK_PERMISSION_URI)
                && !template.url().startsWith(AuthConstants.CHECK_ROLE_URI)) {
            template.header(RootContext.KEY_XID, currentXid);
        }
    }
}
